﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TodoList.Data;
using TodoList.WebApi.DTOs;
using TodoList.WebApi.Mapper;

namespace TodoList.WebApi.Controllers
{
	[ApiController]
	[Route("api/[controller]")]
	public class TodoListController(ApplicationDbContext db) : ControllerBase
	{
		[HttpPost]
		public async Task<IActionResult> CreateAsync([FromBody] CreateTodoItemRequest request)
		{
			var item = request.ToEntity();
			db.TodoItems.Add(item);
			await db.SaveChangesAsync();
			return Ok("Todo item created successfully");
		}

		[HttpPut("{id:int}")]
		public async Task<IActionResult> UpdateAsync(int id, [FromBody] UpdateTodoItemRequest request)
		{
			var item =  await db.TodoItems.FindAsync(id);
			if (item == null)
			{
				return NotFound("Todo item not found");
			}

			item.UpdateEntity(request);
			db.TodoItems.Update(item);
			await db.SaveChangesAsync();
			return Ok("Todo item updated successfully");
		}

		[HttpDelete("{id:int}")]
		public async Task<IActionResult> DeleteAsync(int id)
		{
			var item = await db.TodoItems.FindAsync(id);
			if (item == null)
			{
				return NotFound("Todo item not found");
			}

			db.TodoItems.Remove(item);
			await db.SaveChangesAsync();
			return Ok("Todo item deleted successfully");
		}

		[HttpGet]
		public async Task<IActionResult> GetListAsync()
		{
			var items = await db.TodoItems.ToListAsync();
			return Ok(items);
		}
	}
}
